package com.app.service.impl;

import com.app.entity.Params.ProductSearchParams;
import com.app.entity.Product;
import com.app.mapper.ProductMapper;
import com.app.service.ProductService;
import com.app.util.PageResult;
import com.app.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lkg
 * @since 2021-04-14
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    @Override
    public PageResult findProductByAdmin(ProductSearchParams productSearchParams) {
        Page<Product> page = new Page<>(productSearchParams.getPage(), productSearchParams.getLimit());
        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotEmpty(productSearchParams.getCid())) {
            queryWrapper.eq("cid", productSearchParams.getCid());
        }
        if (StringUtils.isNotEmpty(productSearchParams.getPname())) {
            queryWrapper.like("pname", productSearchParams.getPname());
        }
        queryWrapper.orderByDesc("pdate");
        page = productMapper.selectPage(page, queryWrapper);
        return PageResult.success(page.getTotal(), page.getRecords());
    }

    @Override
    public Result updateProductByAdmin(Product product) {
        if (StringUtils.isNotEmpty(product.getPid())) {
            productMapper.updateById(product);
            return Result.success();
        }
        product.setPdate(new Date());
        productMapper.insert(product);
        return Result.success();
    }
}
